
// pages/index/index.js
const { todoManager, tagManager } = require('../../utils/cloud')
const { formatDateTime, compareDateTime } = require('../../utils/dateHelper')
const { toast, dialog, nav, errorHandler } = require('../../utils/uiHelper')

const app = getApp()

Page({
  data: {
    todos: [],
    isLogin: false,
    filterType: 'all', // all, pending, completed
    selectedTags: [],
    availableTags: [],
    searchKeyword: '',
    sortType: 'time', // time, status
    isLoading: false
  },

  onLoad: async function() {
    // 检查登录状态
    const isLogin = app.globalData.isLogin
    this.setData({ isLogin })
    
    if (isLogin) {
      await this.loadInitialData()
    }
  },

  onShow: async function() {
    if (this.data.isLogin) {
      await this.loadTodos()
    }
  },

  // 下拉刷新
  onPullDownRefresh: async function() {
    if (this.data.isLogin) {
      await this.loadTodos()
    }
    wx.stopPullDownRefresh()
  },

  // 加载初始数据
  async loadInitialData() {
    try {
      toast.loading('加载中...')
      await Promise.all([
        this.loadTodos(),
        this.loadTags()
      ])
    } catch (err) {
      errorHandler.handle(err, '加载失败')
    } finally {
      toast.hideLoading()
    }
  },

  // 加载待办事项列表
  async loadTodos() {
    try {
      this.setData({ isLoading: true })
      
      const result = await todoManager.listTodos({
        status: this.data.filterType === 'all' ? undefined : 
               this.data.filterType === 'completed'
      })

      if (result.code === 0) {
        // 处理待办事项数据
        const todos = result.data.map(todo => ({
          ...todo,
          displayTime: formatDateTime.friendly(todo.reminderTime),
          isOverdue: !todo.status && compareDateTime.isBeforeNow(todo.reminderTime)
        }))

        // 应用筛选和排序
        const filteredTodos = this.filterAndSortTodos(todos)
        
        this.setData({ todos: filteredTodos })
      } else {
        throw new Error(result.msg)
      }
    } catch (err) {
      errorHandler.handle(err, '加载待办事项失败')
    } finally {
      this.setData({ isLoading: false })
    }
  },

  // 加载标签列表
  async loadTags() {
    try {
      const result = await tagManager.listTags()
      if (result.code === 0) {
        this.setData({ availableTags: result.data })
      } else {
        throw new Error(result.msg)
      }
    } catch (err) {
      errorHandler.handle(err, '加载标签失败')
    }
  },

  // 筛选和排序待办事项
  filterAndSortTodos(todos) {
    let filteredTodos = [...todos]
    
    // 根据标签筛选
    if (this.data.selectedTags.length > 0) {
      filteredTodos = filteredTodos.filter(todo => 
        todo.tags.some(tag => this.data.selectedTags.includes(tag))
      )
    }

    // 根据关键词搜索
    if (this.data.searchKeyword) {
      const keyword = this.data.searchKeyword.toLowerCase()
      filteredTodos = filteredTodos.filter(todo => 
        todo.title.toLowerCase().includes(keyword) || 
        todo.content.toLowerCase().includes(keyword)
      )
    }

    // 排序
    filteredTodos.sort((a, b) => {
      if (this.data.sortType === 'time') {
        return new Date(b.reminderTime) - new Date(a.reminderTime)
      } else {
        // 按状态排序：未完成在前，相同状态按时间倒序
        if (a.status === b.status) {
          return new Date(b.reminderTime) - new Date(a.reminderTime)
        }
        return a.status ? 1 : -1
      }
    })

    return filteredTodos
  },

  // 切换筛选类型
  async onFilterChange(e) {
    const type = e.currentTarget.dataset.type
    this.setData({ filterType: type })
    await this.loadTodos()
  },

  // 切换排序方式
  async onSortChange(e) {
    const type = e.currentTarget.dataset.type
    this.setData({ sortType: type })
    await this.loadTodos()
  },

  // 标签选择
  async onTagSelect(e) {
    const tag = e.currentTarget.dataset.tag
    const selectedTags = [...this.data.selectedTags]
    const index = selectedTags.indexOf(tag)

    if (index === -1) {
      selectedTags.push(tag)
    } else {
      selectedTags.splice(index, 1)
    }

    this.setData({ selectedTags })
    await this.loadTodos()
  },

  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    // 使用节流函数延迟加载
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
    this.searchTimer = setTimeout(() => {
      this.loadTodos()
    }, 500)
  },

  // 切换待办事项状态
  async toggleTodoStatus(e) {
    try {
      const id = e.currentTarget.dataset.id
      const result = await todoManager.toggleTodoStatus(id)
      
      if (result.code === 0) {
        // 更新本地数据
        const todos = this.data.todos.map(todo => {
          if (todo._id === id) {
            return { ...todo, status: result.data.status }
          }
          return todo
        })
        this.setData({ todos })
        toast.success('状态已更新')
      } else {
        throw new Error(result.msg)
      }
    } catch (err) {
      errorHandler.handle(err, '更新状态失败')
    }
  },

  // 删除待办事项
  async deleteTodo(e) {
    try {
      const id = e.currentTarget.dataset.id
      const confirmed = await dialog.confirm('确定要删除这个待办事项吗？')
      
      if (confirmed) {
        const result = await todoManager.deleteTodo(id)
        
        if (result.code === 0) {
          const todos = this.data.todos.filter(todo => todo._id !== id)
          this.setData({ todos })
          toast.success('删除成功')
        } else {
          throw new Error(result.msg)
        }
      }
    } catch (err) {
      errorHandler.handle(err, '删除失败')
    }
  },

  // 跳转到编辑页面
  navigateToEdit(e) {
    const id = e.currentTarget.dataset.id
    nav.to(`/pages/edit/index?id=${id}`)
  },

  // 跳转到添加页面
  navigateToAdd() {
    if (!app.checkLogin()) return
    nav.to('/pages/edit/index')
  }
})